<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>实时天气</title>
    <link rel="stylesheet" href="../common/style/reset.css" />
    <style>
      .view {
        width: 100%;
        height: 100%;
        /* margin: 20px; */
      }

      .day-theme {
        --bg-shallow: rgb(235, 232, 232);
        --bg-deep: rgb(67, 122, 255);
        --bg-color: rgb(67, 122, 255);
        /* --color: rgb(51, 51, 51); */
        --color: rgb(255, 255, 255);
      }

      .night-theme {
        --bg-shallow: rgb(4, 4, 73);
        --bg-deep: rgb(0, 0, 0);
        --bg-color: rgb(4, 4, 73);
        --color: rgb(255, 255, 255);
      }

      .weather-box {
        width: 100%;
        height: 100%;
        background-color: var(--bg-color);
        background: linear-gradient(
          to bottom,
          var(--bg-deep),
          var(--bg-shallow)
        );
        position: relative;
        transition: all 1s;
        color: var(--color);
        padding: 5vw;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
      }

      .weather-icon {
        position: absolute;
        width: 40%;
        right: 0;
        top: 0;
        z-index: 0;
        /* 旋转 360 */
        transform-origin: 150% -50%;
        /* transform: rotate(360deg); */
      }

      .icon-rotate {
        transition: all 1s;
        transform: rotate(360deg);
      }

      .weather-icon img {
        width: 100%;
        height: 100%;
      }

      .weather-feelsLike {
        position: relative;
        font-size: 20vw;
        font-weight: 700;

      }

      .weather-city{
        font-size: 10vw;
      }

      .weather-text {
        font-size: 10vw;
        font-weight: 700;
      }
      .weather-windDir {
        font-size: 10vw;
        color: var(--color);
      }
    </style>
  </head>
  <body>
    <div class="view">
      <div class="weather-box day-theme">
        <div class="weather-icon">
          <img data-id="clear" src="./images/clear.png" alt="" />
        </div>
        <div class="weather-feelsLike">--°</div>
        <div class="weather-time"></div>
        <div class="weather-city"></div>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <div class="weather-text"></div>
          <div class="weather-windDir"></div>
        </div>
      </div>
    </div>
  </body>
  <script type="module" src="../common/js/setting.js"></script>
  <script type="module" src="../common/js/menu.js"></script>
  <script type="module" src="../common/js/move.js"></script>
  <script type="module" src="../common/js/counter.js"></script>
  <script type="module">
    import { setInterval } from '../common/utils/utils.js'

    const weatherIconEl = document.querySelector(".weather-icon");
    const weatherImgEl = document.querySelector(".weather-icon img");
    const weatherBoxEl = document.querySelector(".weather-box");
    const weatherFeelsLikeEl = document.querySelector(".weather-feelsLike");
    const weatherTimeEl = document.querySelector(".weather-time");
    const weatherCityEl = document.querySelector(".weather-city");
    const weatherTextEl = document.querySelector(".weather-text");
    const weatherWindDirEl = document.querySelector(".weather-windDir");

    let data = {
      locationId: '',
      city: '',
    }

    let weather = [];

    if(window.ipcRenderer){
      window.ipcRenderer.on('toParent', (event, res)=>{
        data.locationId = res.data.locationId;
        data.city = res.data.city;
        getWeather()
        window.sendSaveData(data)
      })

      window.ipcRenderer.on('init', (event, res)=>{
        data.locationId = res.locationId;
        data.city = res.city;
        getWeather()
      })
    }

    const weatherData = {
      clear: ["晴"],
      partly_cloudy: ["多云", "少云", "晴间多云"],
      yin: ["阴"],
      rain: [
        "雨",
        "小雨",
        "中雨",
        "大雨",
        "极端降雨",
        "毛毛雨/细雨",
        "暴雨",
        "大暴雨",
        "特大暴雨",
        "	冻雨",
        "小到中雨",
        "	中到大雨",
        "大到暴雨",
        "暴雨到大暴雨",
        "大暴雨到特大暴雨",
      ],
      thundershowers: [
        "雷阵雨",
        "强雷阵雨",
        "雷阵雨伴有冰雹",
        "阵雨",
        "强阵雨",
        "雷阵雨伴有冰雹",
        "小到中雨",
        "中到大雨",
        "大到暴雨",
        "暴雨到大暴雨",
        "大暴雨到特大暴雨",
        "阵雨",
        "强阵雨"],
      snow: [
        "小雪",
        "中雪",
        "大雪",
        "暴雪",
        "雨夹雪",
        "雨雪天气",
        "阵雨夹雪",
        "阵雪",
        "小到中雪",
        "中到大雪",
        "大到暴雪",
        "阵雨夹雪",
        "雪",
      ],
      fog: [
        "雾",
        "薄雾",
        "雾天",
        "霾",
        "扬沙",
        "浮尘",
        "浓雾",
        "强浓雾",
        "大雾",
        "中度霾",
        "重度霾",
        "严重霾",
      ],
    };
    
   
    
    let tag = 0;
    const weatherNow = async () => {
      let res = await fetch(
        `https://devapi.qweather.com/v7/weather/now?key=52333e1e98e0489cb4d65a6973051a95&location=${data.locationId}`
      );
      let d = await res.json();
      return {
        fxLink: d.fxLink,
        ...d.now
      };
    };

    const weatherDaily = async () => {
      let res = await fetch(
        `https://devapi.qweather.com/v7/weather/7d?key=52333e1e98e0489cb4d65a6973051a95&location=${data.locationId}`
      );
      let d = await res.json();
      return d.daily.map(item=>{
        return {
          ...item,
          fxLink: d.fxLink,
        }
      });
    };

    const getWeather = async () => {
      if(!data.locationId)return '';
      weatherCityEl.innerText = data.city;
      let res = await Promise.all([weatherNow(), weatherDaily()]);
      let [now, daily] = res;

      weather = [{ ...now, ...daily[0] }, ...daily.slice(1)];
      switchDay()
      render()
    };

   
    document.onclick = window.triggerHandle(() => {
      utools.shellOpenExternal(weather[tag].fxLink)
    });

    const isState = () => {
      // 获取 年、月、日
      let now = new Date();
      let year = now.getFullYear();
      let month = now.getMonth() + 1;
      let day = now.getDate();
      let sunrise = new Date(`${year}-${month}-${day} ${weather[0].sunrise}`).getTime()
      let sunset = new Date(`${year}-${month}-${day} ${weather[0].sunset}`).getTime()
      let dateTime = now.getTime();
      if(sunrise <= dateTime && dateTime <= sunset){
        return true
      }else{
        return false
      }
       
    }

    let mark = false;
    const switchDay = () => {
       
      // weatherTextEl.innerText
      let bool = isState()

      let name = ''
      for(let key in weatherData){
        let weatherString = tag ? weather[tag].textDay : weather[tag].text
        if(weatherData[key].includes(weatherString)){
          name = key
          break;
        }
      }

      if(bool){
        weatherBoxEl.classList.add("day-theme");
        weatherBoxEl.classList.remove("night-theme");
      }else{
        weatherBoxEl.classList.add("night-theme");
        weatherBoxEl.classList.remove("day-theme");
        if(name === 'clear' || name === 'partly_cloudy'){
          name = 'dark-' + name;
        }
      }

      if(mark){
        weatherImgEl.src = `./images/${name}.png`
        return
      }
      mark = true
      weatherIconEl.classList.add("icon-rotate");
      setTimeout(()=>{ 
        weatherImgEl.src = `./images/${name}.png`
      }, 100)
      // weatherBoxEl.classList.toggle("day-theme");
      // weatherBoxEl.classList.toggle("night-theme");
      setTimeout(() => {
        weatherIconEl.classList.remove("icon-rotate");
        mark = false
      }, 1000);
    }

    const convertToDateTimestamp = (dateString) => {
      const date = new Date(dateString);

      const milliseconds = date.getTime();

      return timestamp;
    }

    const render = () => {
      if(tag === 0){
        weatherFeelsLikeEl.innerText = weather[tag].temp + "°";
        weatherFeelsLikeEl.title = weather[tag].tempMin + "-" + weather[tag].tempMax + "°";
        weatherTextEl.innerText = weather[tag].text;
        weatherWindDirEl.innerText = weather[0].windDir + " " + weather[tag].windScale;
        weatherTimeEl.innerText = tag === 0 ? '今天' : (tag === 1 ? '明天' : weather[tag].fxDate)
      }else{
        weatherFeelsLikeEl.innerText = weather[tag].tempMin + "-" + weather[tag].tempMax + "°";
        weatherFeelsLikeEl.title = ''
        weatherTextEl.innerText = weather[tag].textDay;
        weatherWindDirEl.innerText = weather[0].windDirDay + " " + weather[tag].windScaleDay;
        weatherTimeEl.innerText = tag === 0 ? '今天' : (tag === 1 ? '明天' : weather[tag].fxDate)
      }
    };

    getWeather()
    setInterval(getWeather, 30 * 60 * 1000)

    window.getData = ()=>data


    const handleWheel = (e) => {
       // 阻止默认行为，比如页面滚动
        event.preventDefault();
        if(!weather.length)return;
        // 获取滚动的方向
        let deltaY = 0;
        if (event.deltaY !== undefined) {
          deltaY = event.deltaY;
        } else if (event.wheelDeltaY !== undefined) {
          deltaY = -event.wheelDeltaY;
        }

        // 根据滚动的方向做相应的处理
        if (deltaY > 0) {
          if(tag < weather.length - 1){
            tag++;
          }else{
            tag = 0
          }
        } else if (deltaY < 0) {
          if(tag > 0){
            tag--;
          }else{
            tag = weather.length - 1
          }
        }

        switchDay()
        render()
    }
    document.querySelector('body').addEventListener('wheel', handleWheel, { passive: false });

 
  </script>
</html>
